package com.lhs.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.InputStream;
import java.util.UUID;

@Component
public class OssUtil {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    // 上传文件，返回访问URL
    public String upload(InputStream inputStream, String originalFilename) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString().replace("-", "")
                + "_" + originalFilename;

        // 上传
        ossClient.putObject(bucketName, fileName, inputStream);

        // 关闭客户端
        ossClient.shutdown();

        // 返回文件URL
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }
}
